//
//  SiSaveDetailVC.swift
//  SiliUtility
//
//  Created by Li Dong on 2023/10/18.
//

import UIKit
import SnapKit

class SiSaveDetailVC: SiBaseVC {
    
    lazy var scrollView = UIScrollView()
    var collectionView: UICollectionView!
    var bottomView: SiSaveProgressView!
    
    private let CellID = "DaysCellID"
    
    var startDate: Date!
    var startAmount: Double = 0
    var addNumber: Double = 0
    var totalAmount: Double = 0
    
    var days: Int = 0
    
    init(startDate: Date!, startAmount: Double, addNumber: Double, totalAmount: Double) {
        super.init(nibName: nil, bundle: nil)
        self.startDate = startDate
        self.startAmount = startAmount
        self.addNumber = addNumber
        self.totalAmount = totalAmount
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        title = "365存钱"
        initViews()
        configData()
    }
    
    func initViews() {
        scrollView.backgroundColor = .clear
        view.addSubview(scrollView)
        scrollView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        let w = CGFloat.screenWidth/15
        layout.itemSize = CGSize(width: w, height: 22)
        
        collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.backgroundColor = .clear
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(UINib(nibName: "SiDayCell", bundle: nil), forCellWithReuseIdentifier: CellID)
        scrollView.addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.width.equalTo(view)
            make.top.equalTo(20)
            make.height.equalTo(collectionView.snp.width)
        }
        
        bottomView = SiSaveProgressView()
        scrollView.addSubview(bottomView)
        bottomView.snp.makeConstraints { make in
            make.left.equalTo(25)
            make.right.equalTo(-25)
            make.top.equalTo(collectionView.snp.bottom).offset(30)
            make.height.equalTo(171)
            make.bottom.equalToSuperview()
        }
    }
    

    private func configData() {
        guard let endDate = s_calendar.date(byAdding: .day, value: 364, to: startDate) else {
            return
        }
        bottomView.startLabel.text = "开始时间：" + df.string(from: startDate)
        bottomView.endLabel.text = "结束时间：" +  df.string(from: endDate)
        var totalStr = String(format: "￥%.2f", totalAmount)
        if totalStr.hasSuffix(".00") {
            totalStr = totalStr.replacingOccurrences(of: ".00", with: "")
        }
        if totalStr.hasSuffix(".0") {
            totalStr = totalStr.replacingOccurrences(of: ".0", with: "")
        }
        bottomView.totalAmountLabel.text = totalStr
        days = max((s_calendar.dateComponents([.day], from: startDate, to: Date()).day ?? 1) + 1, 0)
        if days > 365 {
            days = 365
        }
        bottomView.daysLabel.text = "\(days)"
        //当前累计   计算预计总金额S = n/2 × (2a + (n-1) × d)
        let current = days <= 0 ? 0 : Double(days)/2 * (2*startAmount + Double(days-1)*addNumber)
        bottomView.currentTotalLabel.text = String(format: "￥%.2f", current)
        bottomView.amountProgressView.progress = current/totalAmount
        bottomView.amountProgressLabel.text = String(format:"%.0f%%", current/totalAmount*100)
        bottomView.daysProgressView.progress = Double(days)/365
        bottomView.daysProgressLabel.text = String(format:"%.0f%%", Double(days)/365*100)
    }
    
    lazy var df: DateFormatter = {
        let temp = DateFormatter()
        temp.dateFormat = "yyyy.MM.dd"
        return temp
    }()

    lazy var s_calendar: Calendar = {
        let temp = Calendar(identifier: .gregorian)
        return temp
    }()
}

extension SiSaveDetailVC: UICollectionViewDelegate, UICollectionViewDataSource {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        365
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CellID, for: indexPath) as! SiDayCell
        //An=a1+（n-1）*d
        var str = String(format: "%.2f", startAmount + Double(indexPath.row)*addNumber)
        if str.hasSuffix(".00") {
            str = str.replacingOccurrences(of: ".00", with: "")
        }
        if str.hasSuffix(".0") {
            str = str.replacingOccurrences(of: ".0", with: "")
        }
        cell.numLabel.text = str
        cell.numLabel.backgroundColor = (indexPath.row + 1) <= days ? UIColor.init(hex: 0x7339DD) : UIColor.init(hex:0xF1E8FF)
        cell.numLabel.textColor = (indexPath.row + 1) <= days ? UIColor.white : UIColor.init(hex: 0x333333)
        return cell
    }
}
